import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { Link, Redirect, useHistory } from 'react-router-dom'
import * as useActionCreators from '../store/actionCreators/user'
import MessageErr from '../components/MessageErr';


function Login(props) {
  const { onLogin, token, errors, clearErr } = props
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const history = useHistory()
  
  useEffect(() => {
    if (token) {
      return <Redirect to="/" />
    }
  }, [token])
  

  useEffect(() => () => {
    clearErr()
  }, [clearErr])

  return (
    <div className="auth-page">
      <div className="container page">
        <div className="row">
          {
            <div className="col-md-6 offset-md-3 col-xs-12">
              <h1 className="text-xs-center">Sign in</h1>
              <p className="text-xs-center">
                  <Link to="/register">Need an account?</Link>
              </p>
              <MessageErr errors={errors}/>
              <form>

                <fieldset
                  className="form-group">
                  <input
                    className="form-control form-control-lg"
                    name="user.email"
                    placeholder="Email"
                    value={email}
                    onChange={e => setEmail(e.target.value)} />
                </fieldset>

                <fieldset
                  className="form-group">
                  <input
                    className="form-control form-control-lg"
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={e => setPassword(e.target.value)} />
                </fieldset>

                <button
                  className="btn btn-lg btn-primary pull-xs-right"
                  type="button"
                  onClick={() => onLogin({ email, password }, history)}>
                    Sign in
                </button>
              </form>
            </div>
          }
        </div>
      </div>
    </div>
  )
}

const mapStateToProps = state => ({
  token: state.user.token,
  errors: state.user.errors
})

const mapDispatchToProps = (dispatch) => ({
  onLogin: (payload, history) => {
    dispatch(useActionCreators.login(payload, history))
  },
  clearErr: () => {
    dispatch(useActionCreators.setErrList(null))
  }
})


export default connect(mapStateToProps, mapDispatchToProps)(Login)